//
//  LCHomeTableViewController+LoadData.m
//  JKFuYinProject
//
//  Created by jiukuyinyue on 2017/10/23.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCHomeTableViewController+LoadData.h"

@implementation LCHomeTableViewController (LoadData)
//将首页的前10条数据赋值到 beautifulEssayListArray 属性里
- (void)setupPageOneData:(NSArray *)dictArr2 {
    if (dictArr2.count == 0) {
        return;
    }
    NSMutableArray *mArray = [[NSMutableArray alloc] initWithArray:[NSMutableArray yy_modelArrayWithClass:[BeautifulEssayModel class] json:dictArr2]];
    self.beautifulEssayListArray = mArray;
}
///增加广告
- (void)addBaiduAd {
    BeautifulEssayModel *model = [[BeautifulEssayModel alloc] init];
    model.type = @"0";
    model.id =
    [NSString stringWithFormat:@"%zd",self.listPageNum-1];
    if (self.listPageNum == 1) {
        [self.beautifulEssayListArray insertObject:model atIndex:arc4random_uniform(4)+1];
    }else{
        [self.beautifulEssayListArray insertObject:model atIndex:self.beautifulEssayListArray.count-arc4random_uniform(5)];
    }
}

//添加 数据 后 刷新界面显示数据
- (void)refreshTableView {
    
    //------------------------------------------------------------------------------------
    if (self.adsArray.count > 0 && self.listPageNum < [self.adViewArray count] && self.listPageNum > 1) {
        [self addBaiduAd];
    }
    if (self.listPageNum == 1) {
        if (self.adsArray.count > 0) {
            [self addBaiduAd];

        }else{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.adsArray.count > 0 && self.listPageNum == 1) {
                    [self addBaiduAd];
                    [self.tableView reloadData];
                }
            });
        }
    }
    //------------------------------------------------------------------------------------
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.55 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableView.mj_header endRefreshing];
        });
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    }];
}

- (void)netError {
    Reachability *reach = [Reachability reachabilityWithHostName:@"http://baidu.com"];
    if ([reach currentReachabilityStatus] == NotReachable){
        [SVProgressHUD showErrorWithStatus:NoNetwork];
        [SVProgressHUD dismissWithDelay:0.5];
    }
}

-(void)loadDataWithPage:(BOOL)page{
    
    NetworkTool *networkTool = [NetworkTool sharedInstance];
    NSString *urlString = [NSString stringWithFormat:@"%@",http_shengjing];
    [networkTool POSTFuYinWithUrlString:HOME_CAROUSEL input:@{} success:^(NSDictionary *dict) {
        NSArray *dictArr2 = dict[@"data"];
        self.cycleArray = [NSArray yy_modelArrayWithClass:[LCCycleModel class] json:dictArr2];
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [self loadCycleScrollViewData];
        }];
    } failure:^(NSError *error) {   NSLog(@"error = %@", error);
    }];
    
#pragma mark -  wenzhang shiping gequ ************* 多图 单张图 视频文章-
    if (page) {
        self.listPageNum += 1;
    } else {
        self.listPageNum = 1;
    }
    //首页文章
    NSDictionary *essayParameters = @{@"interface":@"get_home_list",
                                      @"id":@(0),
                                      @"page":@(self.listPageNum),
                                      @"size":@(5)
                                      };
    YYCache *yyCache=[YYCache cacheWithName:@"LCCache"];
    [yyCache.diskCache setCostLimit:10*1024*1024];//磁盘最大缓存开销
    [yyCache.diskCache setAutoTrimInterval:60*60*24*2];//设置磁盘lru动态清理频率 默认 60秒
    NSString *key= [NSString stringWithFormat:@"%@",@"keyHomeCache"];
    
    //------------------------------------------------------------------------------------
    if (page == NO && [yyCache containsObjectForKey:key]) {
        //根据key读取数据
        id vuale = [yyCache objectForKey:key];
        self.beautifulEssayListArray = [NSArray yy_modelArrayWithClass:[BeautifulEssayModel class] json:vuale].mutableCopy;
        NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,5)];
        if (self.beautifulEssayListArray.count >= 5) {
            self.beautifulEssayListArray = [self.beautifulEssayListArray objectsAtIndexes:indexes].mutableCopy;//只读10条
        }
        self.isCache = YES;
        [self.tableView reloadData];
    }
    //------------------------------------------------------------------------------------
    
    if (self.isCache && page) {//假如缓存且上拉加载更多就读两页数据
        essayParameters = @{@"interface":@"get_home_list",
                            @"id":@(0),
                            @"page":@(1),
                            @"size":@(10)
                            };
        self.listPageNum = 2;
    }
    
    [networkTool POSTFuYinWithUrlString:urlString input:essayParameters success:^(NSDictionary *dict) {
        NetWorkModel *netWorkModel = [NetWorkModel yy_modelWithJSON:dict];
        NSArray *dictArr2 = netWorkModel.data;
        //        NSLog(@"dictArr2 = %@", dictArr2);
        NSMutableArray *mArray = [NSArray yy_modelArrayWithClass:[BeautifulEssayModel class] json:dictArr2].mutableCopy;
        
        if (page/**上拉加载更多*/) {
            if (self.isCache && mArray.count > 0) {
                NSLog(@"缓存mArray = %lu", (unsigned long)mArray.count);
                self.beautifulEssayListArray = mArray;
                //假如缓存读出数据就标记已不是缓存
                self.isCache = NO;
            }else{
                [self.beautifulEssayListArray addObjectsFromArray:mArray];
            }
            if (mArray == nil) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.41 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                });
            }
        }else{
            self.beautifulEssayListArray = mArray;//将首页的前10条数据赋值到 beautifulEssayListArray 里
            if (mArray.count > 0) {
                self.isCache = NO;
            }
        }
        [self refreshTableView];//刷新界面
        
        ///进行缓存

        NSMutableArray *cacheMutableArray = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < self.beautifulEssayListArray.count; i++) {
            BeautifulEssayModel *model = self.beautifulEssayListArray[i];
            NSDictionary *json = [model yy_modelToJSONObject];
            [cacheMutableArray addObject:json];
        }
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            if (cacheMutableArray) {
                [yyCache setObject:cacheMutableArray forKey:key];//添加数据到yyCache里缓存下来
            }
        });
    } failure:^(NSError *error) {
        ///网络错误提示
        [self netErrorWithStatus:NoNetwork];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{

            if ([yyCache containsObjectForKey:key]) {
                //根据key读取数据
                id vuale = [yyCache objectForKey:key];
                self.beautifulEssayListArray = [NSArray yy_modelArrayWithClass:[BeautifulEssayModel class] json:vuale].mutableCopy;
                if (!page) {//第一页
                    NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,5)];
                    if (self.beautifulEssayListArray.count >= 5) {
                        self.beautifulEssayListArray = [self.beautifulEssayListArray objectsAtIndexes:indexes].mutableCopy;//只读10条
                    }
                    self.isCache = YES;
                }else{
                    self.isCache = YES;
                }
            }

            if (page) {
                self.listPageNum = self.listPageNum - 1;//翻页
            }

            [self refreshTableView];//刷新界面
            //            NSLog(@"error = %@", error);
        });
    }];

}

-(void)loadCycleScrollViewData{
    NSMutableArray *imagesURLStrings = [NSMutableArray arrayWithCapacity:self.cycleArray.count];
    for (LCCycleModel *cycleDict in self.cycleArray) {
        if (cycleDict != nil) {
            [imagesURLStrings addObject:cycleDict.pic];
        }
    }
    if (imagesURLStrings.count == 0) {
        self.cycleScrollView.imageURLStringsGroup = @[@"devotion_bannerA",@"devotion_bannerB"];
    }else{
        self.cycleScrollView.imageURLStringsGroup = imagesURLStrings;
    }
}

- (void)netErrorWithStatus:(NSString *)status {
    Reachability *reach = [Reachability reachabilityWithHostName:@"http://baidu.com"];
    if ([reach currentReachabilityStatus] == NotReachable){
        [SVProgressHUD showErrorWithStatus:status];
        [SVProgressHUD dismissWithDelay:0.5];
    }
}

@end
